<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 娴佸勾 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use \OSS\OssClient;
use think\Db;

function curl_post($url,$headers,$body){
    

    
   
    //$postBody    = json_encode($body);
   // echo $postBody;exit;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
    curl_setopt ( $curl , CURLOPT_POST ,  1 ) ;
    curl_setopt($curl, CURLINFO_HEADER_OUT, true);
    

    
    $data = curl_exec($curl);

    return $data;
}

function tts_api($text,$language="zh"){
    $access_token=get_tss_token();
    
    $headers = array();
    $body=array("access_token"=>$access_token,
        "domain"=>1,
        "language"=>$language,
        "voice_name"=>"Zhuxiaomei",
        "audiotype"=>3,
        "text"=>$text
    );
    $curlPost=http_build_query($body);
    // echo $curlPost;exit;
    $url="https://openapi.data-baker.com/tts";
    $data=curl_post($url, $headers, $curlPost);
    return $data;
}


function tts_one($text,$type,$a_id,$language,$file_type){

    $data=tts_api($text,$language);
    
    
    if(isJsonString($data)){
        $ret=json_decode($data,true);
        if(isset($ret['err_no'])){
           
            if($language=="zh"){
               $sql="update content set is_audio_ch =2  where a_id=".$a_id." limit 1";
                Db::execute($sql);
            }
            else{
                $sql="update ts_info_en set is_audio_en =2  where a_id=".$a_id." limit 1";
                Db::execute($sql);
            }
            return $ret['err_no']."-".date('Y-m-d H:i:s')."\n";
        }
    }
    else{
        
        
        $audio_name=$a_id."-".$file_type."-".$language.".mp3";
        $file_local_path = '/var/www/timo/data/temp_mp3/'.$audio_name;
        
        file_put_contents($file_local_path, $data);
        if(file_exists($file_local_path)){
            $oss_img_url = aliyun($audio_name,$type);

            $sql="insert into  file_list set oss_key='".$oss_img_url."', a_id=".$a_id.",type = '".$file_type."',language = '".$language."',bucket='timo-video' ";
            
            Db::execute($sql);
            if($language=="zh"){
                $sql="update content set is_audio_ch =1  where a_id=".$a_id." limit 1";
                Db::execute($sql);
            }
            else{
                $sql="update ts_info_en set is_audio_en =1  where a_id=".$a_id." limit 1";
                Db::execute($sql);
            }
            delfile($audio_name);
            return 1;
        }
    }
}

function tts_task($language="zh",$limit=1){
    
    if($language=="zh"){
        $s=" SELECT * FROM content WHERE  is_audio_ch =0 limit ".$limit;
        $result = Db::query($s);
    }
    else{        
        $s=" SELECT * FROM ts_info_en  WHERE  is_audio_en =0 limit ".$limit;
        $result = Db::query($s);
    }
    foreach ($result as $k =>$v){
        $text=$v['name'];
        $type=$v['type'];
        $a_id=$v['a_id'];
        $status=tts_one($text,$type,$a_id,$language); 
        echo $status;
    }
    echo  "sucess-".date('Y-m-d H:i:s')."\n";
    
    exit();
    
}


function isJsonString($str = '')
{
    $jObject = json_decode($str);
    return (is_object($jObject)) ? true : false;
}
function curl_get($url){
    //初始化
    $curl  =  curl_init ( ) ;
    //设置抓取的url
    curl_setopt ( $curl , CURLOPT_URL ,  $url ) ;
    curl_setopt ( $curl , CURLOPT_COOKIE ,  'OCSSID=4df0bjva6j7ejussu8al3eqo03' ) ;
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'); 
    //设置头文件的信息作为数据流输出
    curl_setopt ( $curl , CURLOPT_HEADER ,  0) ;
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt ( $curl , CURLOPT_RETURNTRANSFER ,  false) ;
    //执行命令
    $data  =  curl_exec ( $curl ) ;
    //关闭URL请求
    curl_close ( $curl ) ;
    //显示获得的数据
    return $data;
}


function get_tss_token(){
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);
    //$redis->delete("access_token");
    $access_token= $redis->get("access_token") ;
    
    if(isset($access_token)&&$access_token!=''){
        return $access_token;
    }
    else{
       // $client_secret ="f363a8a4b5344608be2ed442bac3687b";
        //$client_id = "0161528d0e324783b217a751938b2f41";
        $client_id = "9e38f735-82b4-4ba5-ae31-b4c25cb3602a";
        $client_secret = "ZDJhNGRiYzItZjE2ZS00MGVhLTgzZjMtMTgxNDljMjE0NzQx";
        $url="https://openapi.data-baker.com/oauth/2.0/token?grant_type=client_credentials&client_secret=".$client_secret."&client_id=".$client_id;
        $content=file_get_contents($url);
        $content=json_decode($content,true);
        $redis->set("access_token", $content['access_token']);
        $expireTime = mktime(23, 59, 59, date("m"), date("d"), date("Y"));
        
        $redis->expireAt("access_token", $expireTime);
        return  $content['access_token'];
    }
}


function createFolder($path) {
    if (!file_exists($path)) {
        createFolder(dirname($path));
        mkdir($path, 0777);
    }
}
/*记录日志*/
function logsave($content){
    // global $host_url;
    if(!file_exists(ROOT_PATH.'data/log')){
        createFolder(ROOT_PATH.'data/log');
    }
    
    if(!file_exists(ROOT_PATH.'data/log/'.date('Y-m-d').'.txt')){
        $f = fopen(ROOT_PATH.'data/log/'.date('Y-m-d').'.txt', "w+");
        chmod(ROOT_PATH.'data/log/'.date('Y-m-d').'.txt',0755);
        fclose($f);
    }
    
    if(!empty($content)){
        $content = "\r\n".date('Y-m-d H:i:s')."：".$content;
        file_put_contents(ROOT_PATH.'data/log/'.date('Y-m-d').'.txt',$content,FILE_APPEND);
    }
    
}



function savefile($url,$filename){
    $file = file_get_contents($url);
    $time = time();
    $file_local_path = '/var/www/timo/data/temp_image/';
    $file_local = $file_local_path .$filename;
    //echo $file_local_path;
    if (!file_exists($file_local_path)) {
        mkdir($file_local_path, 0777);
        @chmod($file_local_path, 0777);
    }
    file_put_contents($file_local, $file);
    return true;
    
}

function delfile($filename){
    $path = '/var/www/timo/data/temp_mp3/'.$filename;
    if (file_exists($path)) {
        return is_file($path) && unlink($path);
    }
}


function aliyun($filename,$type='',$isunlink=false,$bucket="timo-video"){
    $accessKeyId = config('aliyun_oss.accessKeyId');//去阿里云后台获取秘钥
    $accessKeySecret = config('aliyun_oss.accessKeySecret');//去阿里云后台获取秘钥
    $endpoint = config('aliyun_oss.endpoint');//你的阿里云OSS地址
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
    //        判断bucketname是否存在，不存在就去创建
    if( !$ossClient->doesBucketExist($bucket)){
        $ossClient->createBucket($bucket);
    }
    $category=empty($category)?$bucket:$category;
    
   
    $file_path="/var/www/timo/data/temp_mp3/";
    $object ="animal/".$type."/".get_id().".mp3";
   // $file = './uploads\\'.$savePath;//文件路径，必须是本地的。
    $file = $file_path.$filename;
    

    try{
        $ossClient->uploadFile($bucket,$object,$file);
        if ($isunlink==true){
            unlink($file);
        }
    }catch (OssException $e){
        $e->getErrorMessage();
    }
    $oss=config('aliyun_oss.url');
    return $object;
}

function oss_upload_file($folder,$type='',$filename,$isunlink=false,$bucket="timo-public"){
    $accessKeyId = config('aliyun_oss.accessKeyId');//去阿里云后台获取秘钥
    $accessKeySecret = config('aliyun_oss.accessKeySecret');//去阿里云后台获取秘钥
    $endpoint = config('aliyun_oss.endpoint');//你的阿里云OSS地址
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
   // $bucket="timo-public";
    //        判断bucketname是否存在，不存在就去创建
    if( !$ossClient->doesBucketExist($bucket)){
        $ossClient->createBucket($bucket);
    }
    $category=empty($category)?$bucket:$category;
    
    $ext=substr(strrchr($filename, '.'), 1);
    //$file_path="/var/www/timo/data/temp_image/";
    $object ="animal/".$type."/".get_id().".".$ext;
    // $file = './uploads\\'.$savePath;//文件路径，必须是本地的。
    $file = $folder.$filename;
    
    
    try{
        $ossClient->uploadFile($bucket,$object,$file);
        if ($isunlink==true){
            unlink($file);
        }
    }catch (OssException $e){
        $e->getErrorMessage();
    }
    $oss=config('aliyun_oss.url');
    return $object;
}


function ossdown($object,$localfile,$bucket="timo-video"){
    
    $accessKeyId = config('aliyun_oss.accessKeyId');//去阿里云后台获取秘钥
    $accessKeySecret = config('aliyun_oss.accessKeySecret');//去阿里云后台获取秘钥
    $endpoint = config('aliyun_oss.endpoint');//你的阿里云OSS地址
    $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

    $options = array(
        OssClient::OSS_FILE_DOWNLOAD => $localfile
    );
    $ossClient->getObject($bucket, $object, $options);
}


function get_id() {
    $time = substr(date("YmdHis", time()), 3);
    $randNum = randString();
    if (is_numeric($randNum)) {
        //纯数字检测，如果是纯数字，重新调用该方法
        $b = get_id();
        $uuid = $time . $b;
    } else {
        $uuid = $time . $randNum;
    }
    //因为生成的Id是15位的，所以取最后的15位
    return substr($uuid, -15);
}

//生成随机数  纯数字就再次调用
function randString() {
    
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    //    $characters = '0123456789a';
    $randomString = '';
    for ($i = 0; $i < 4; $i++) {
        $randomString .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomString;
}


function catch_img($name){
    
   // echo ROOT_PATH ;exit;
  
    $command="python ".ROOT_PATH."/public/spider.py --name=".$name." 2>error.txt";
  //echo '<br>';
   exec($command,$array,$ret); 
   if(count($array)>0){
       
       return $array[0];
   }
   else {
       return false;
   }


}


function get_audio_time($folder,$language){
    $path = $folder.'audio-'.$language.".mp3";
    $c="/usr/bin/ffmpeg -i " .$path. " 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//";
    
    $time= exec($c);

    if($time!="N/A"){
       $a=explode('.', $time);
        //list($hms, $milli) = explode('.', $time);
        
        $b=explode(':', $a[0]);
        if(isset($b[0])){
            $hours=$b[0];
        }
        else{
            $hours=0;
        }
        
        if(isset($b[1])){
             $minutes = $b[1];
        }
        else{
            $minutes=0;
        }
        //var_dump(isset($b[1]));exit;
        if(isset($b[2])){
            $seconds=$b[2];
        }
        else{
            $seconds=0;
        }
        $total_seconds = ($hours * 3600) + ($minutes * 60) + $seconds;
 
        return $total_seconds;
    }
    else{
        return false;
    }
}


function creat_video_config_file($folder,$language ,$image_count){

    if($image_count>0){
        $time=get_audio_time($folder,$language);

        if($time>0){
            $one_loop_time = $image_count * 3;
            $loop =floor($time/$one_loop_time);
            $file_text="";
            
            
            for($i=0;$i<=$loop;$i++){
                for($j=0;$j<$image_count;$j++){
                    $file_text.="file ".$folder."image".$j.".jpg\nduration 3 \n";
                }
            }
            
            $file_text.="file ".$folder."image".($image_count-1).".jpg";
            
            $config_file = $folder . "/config-".$language.".txt";
            file_put_contents($config_file,$file_text);
            return true;
        }
        else{
            return false;
        }
    }
    else{
        return false;
    }
    
    
}
 
function creat_mp4($config_file,$audio_name,$temp_path,$type,$language){
    if($language=="eng"){
        $temp_video_name_1=$temp_path."temp_en_video_1.mp4";
        $temp_video_name_2=$temp_path."temp_en_video_2.mp4";
        $video_name=$temp_path."video-en.mp4";
    }
    else{
        $temp_video_name_1=$temp_path."temp_cn_video_1.mp4";
        $temp_video_name_2=$temp_path."temp_cn_video_2.mp4";
        $video_name=$temp_path."video-cn.mp4";
    }
    $cmd = "/usr/bin/ffmpeg  -y -threads 2  -f concat -safe 0  -i " .$config_file ." -i ".$audio_name ." -absf aac_adtstoasc  -r 30 -vcodec h264 " .$temp_video_name_1;
     exec($cmd);

     if($type==1){
        $png="/var/www/timo/data/temp_video/zhiwu.png";   
     }
     elseif($type==2 or $type==3){
         $png="/var/www/timo/data/temp_video/dongwu.png";  
     }
     else{
         $png="/var/www/timo/data/temp_video/jujia.png";  
     }
    
     $cmd1="/usr/bin/ffmpeg -threads 5 -y -loop 1 -i ".$png."   -i ".$temp_video_name_1." -filter_complex \"[1] scale=237:153 [over]; [0][over] overlay=64:29\" -shortest ".$temp_video_name_2;
    
     exec($cmd1, $log, $status);
     if($status>0){
         return false;
     }
    // echo $status."<br>";
    // echo date("Y-m-d h:i:s");
     $cmd2="/usr/bin/ffmpeg -threads 5 -y -i ".$temp_video_name_2." -ignore_loop 0 -i /var/www/timo/data/temp_video/maotouyin.gif -filter_complex \"[1] scale=115:125 [over]; [0][over] overlay=0:97\" -shortest ".$video_name;
     exec($cmd2, $log, $status);
     if($status>0){
         return false;
     }
     return true;
}

function creat_mp4_re($config_file,$audio_name,$temp_path,$type,$language){
    if($language=="eng"){
        $temp_video_name_1=$temp_path."temp_en_video_1.mp4";
        $temp_video_name_2=$temp_path."temp_en_video_2.mp4";
        $video_name=$temp_path."video-en.mp4";
        $video_new_name=$temp_path."video-en-264.mp4";
    }
    else{
        $temp_video_name_1=$temp_path."temp_cn_video_1.mp4";
        $temp_video_name_2=$temp_path."temp_cn_video_2.mp4";
        $video_name=$temp_path."video-cn.mp4";
        $video_new_name=$temp_path."video-cn-264.mp4";
    }
     $cmd = "/usr/bin/ffmpeg  -y -threads 2  -f concat -safe 0  -i " .$config_file ." -i ".$audio_name ." -absf aac_adtstoasc    -vcodec h264 " .$temp_video_name_1;
  
    exec($cmd);
    
    if($type==1){
        $png="/var/www/timo/data/temp_video/zhiwu.png";
    }
    elseif($type==2 or $type==3){
        $png="/var/www/timo/data/temp_video/dongwu.png";
    }
    else{
        $png="/var/www/timo/data/temp_video/jujia.png";
    }
    
    $cmd1="/usr/bin/ffmpeg -threads 5 -y -loop 1 -i ".$png."   -i ".$temp_video_name_1." -filter_complex \"[1] scale=237:153 [over]; [0][over] overlay=64:29\" -shortest ".$temp_video_name_2;
    
    exec($cmd1, $log, $status);
    if($status>0){
        return false;
    }
    // echo $status."<br>";
    // echo date("Y-m-d h:i:s");
    $cmd2="/usr/bin/ffmpeg -threads 5 -y -i ".$temp_video_name_2." -ignore_loop 0 -i /var/www/timo/data/temp_video/maotouyin.gif -filter_complex \"[1] scale=115:125 [over]; [0][over] overlay=0:97\" -shortest ".$video_name;
    exec($cmd2, $log, $status);
    if($status>0){
        return false;
    }
    
    $cmd3="/usr/bin/ffmpeg -threads 5   -i ".$video_name."  -vf scale=640:480  -r 30 -vcodec h264 ".$video_new_name;
    exec($cmd3, $log, $status);
    if($status>0){
        return false;
    }
    return true;
}

function suofang($img_path){
    $cmd="/usr/bin/ffmpeg -y -i ".$img_path." -vf 'scale=640:480'  ".$img_path;
    exec($cmd);
}

function strFilter($str){
    $str = str_replace('`', '', $str);
    $str = str_replace('·', '', $str);
    $str = str_replace('~', '', $str);
    $str = str_replace('!', '', $str);
    $str = str_replace('！', '', $str);
    $str = str_replace('@', '', $str);
    $str = str_replace('#', '', $str);
    $str = str_replace('$', '', $str);
    $str = str_replace('￥', '', $str);
    $str = str_replace('%', '', $str);
    $str = str_replace('^', '', $str);
    $str = str_replace('……', '', $str);
    $str = str_replace('&', '', $str);
    $str = str_replace('*', '', $str);
    $str = str_replace('(', '', $str);
    $str = str_replace(')', '', $str);
    $str = str_replace('（', '', $str);
    $str = str_replace('）', '', $str);
    $str = str_replace('-', '', $str);
    $str = str_replace('_', '', $str);
    $str = str_replace('——', '', $str);
    $str = str_replace('+', '', $str);
    $str = str_replace('=', '', $str);
    $str = str_replace('|', '', $str);
    $str = str_replace('\\', '', $str);
    $str = str_replace('[', '', $str);
    $str = str_replace(']', '', $str);
    $str = str_replace('【', '', $str);
    $str = str_replace('】', '', $str);
    $str = str_replace('{', '', $str);
    $str = str_replace('}', '', $str);
    $str = str_replace(';', '', $str);
    $str = str_replace('；', '', $str);
    $str = str_replace(':', '', $str);
    $str = str_replace('：', '', $str);
    $str = str_replace('\'', '', $str);
    $str = str_replace('"', '', $str);
    $str = str_replace('“', '', $str);
    $str = str_replace('”', '', $str);
    $str = str_replace(',', '', $str);
    $str = str_replace('，', '', $str);
    $str = str_replace('<', '', $str);
    $str = str_replace('>', '', $str);
    $str = str_replace('《', '', $str);
    $str = str_replace('》', '', $str);
    $str = str_replace('.', '', $str);
    $str = str_replace('。', '', $str);
    $str = str_replace('/', '', $str);
    $str = str_replace('、', '', $str);
    $str = str_replace('?', '', $str);
    $str = str_replace('？', '', $str);
    return trim($str);
}
